﻿using System.ComponentModel;
using System.Linq.Expressions;
using ZenSystemService.Api.Entities;
using System.Reflection;

namespace ZenSystemService.Api.Utils
{
    public static class StringExtensions
    {
        /// <summary>
        /// Convert string to criteria expression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where">两个条件之间用分割，一个条件中的属性和值用=连接</param>
        /// <returns></returns>
        public static IEnumerable<Expression<Func<T, bool>>> GeneratePredicates<T>(this string where) where T : class
        {
            var result = new List<Expression<Func<T, bool>>>();
            if (!string.IsNullOrEmpty(where))
            {
                var criterias = where.Split('&').Select(c => c.Trim());
                
                foreach (var criteria in criterias)
                {
                    var criteriaPair = criteria.Split('=');
                    var parameter = Expression.Parameter(typeof(T), "x");
                   
                    var property = Expression.Property(parameter, criteriaPair[0]);
                    var fieldType = typeof(T).GetProperties().FirstOrDefault(p => string.Equals(criteriaPair[0], p.Name, StringComparison.OrdinalIgnoreCase))
                        ?.PropertyType;
                    if (fieldType != null)
                    {
                        var fieldValue = ConvertValueToFieldType(criteriaPair[1], fieldType);
                        var valueConstant = Expression.Constant(fieldValue);

                        // 创建比较表达式，例如: x => x.PropertyName == value
                        var predicate = Expression.Lambda<Func<T, bool>>(
                            Expression.Equal(property, valueConstant),
                            parameter
                        );
                        result.Add(predicate);
                    }
                }
            }
            return result;
        }
        private static object ConvertValueToFieldType(object value, Type fieldType)
        {
            // 如果字段类型为null，或者值已经是正确的类型，则直接返回值
            if (fieldType == null || fieldType.IsInstanceOfType(value))
            {
                return value;
            }

            try
            {
                // 使用TypeDescriptor.GetConverter来获取相应的类型转换器
                var converter = TypeDescriptor.GetConverter(fieldType);
                if (converter != null && converter.CanConvertFrom(value.GetType()))
                {
                    return converter.ConvertFrom(value);
                }
            }
            catch
            {
                // 转换失败时的处理逻辑...
            }

            // 如果没有找到合适的转换器，或者转换失败，可以返回null或者抛出异常
            return null;
        }
    }
}